<?php
namespace org\kahikai\database\mysql;

require_once dirname(__FILE__) . '/../PhylogenyDao.php';
require_once dirname(__FILE__) . '/KahikaiMysql.php';
require_once dirname(__FILE__) . '/../../domain/Phylogeny.php';

use org\kahikai\database\PhylogenyDao;
use org\kahikai\domain\Phylogeny;

/**
 * 
 * @author ch4mp
 *
 */
class MysqlPhylogenyDao implements PhylogenyDao {
	
	/**
	 *
	 * @return a list of phulogenic tree source names
	 */
	public function getSources() {
		$sources = array();
		
		$result = KahikaiMysql::query('SELECT DISTINCT name FROM PHILOGENIC_TREE WHERE parent_id is null');
		while($record = $result->fetch_assoc()) {
			array_push($sources, $record['name']);
		}
		$result->close();
		
		return $sources;
	}
	
	/**
	 *
	 * @return an array of phylogeny leaves (last step) by Species id
	 */
	public function getAllSpeciesLeaves() {
		$speciesleaves = array();
		$idMap = array();
		$nodes = array();
		$parents = array();
		
		$result = KahikaiMysql::query('
SELECT p.id, p.name, p.parent_id, sp.species_id
FROM PHILOGENIC_TREE p
LEFT OUTER JOIN SPECIES_PHILOGENY sp
ON p.id=sp.philogeny_leave_id');
		while ($record = $result->fetch_assoc()) {
			$nodes[$record['id']] = new Phylogeny($record['id'], $record['name']);
			if($record['parent_id'] != null) {
				$parents[$record['id']] = $record['parent_id'];
			}
			if($record['species_id'] != null) {
				if(!array_key_exists($record['species_id'], $idMap)) {
					$idMap[$record['species_id']] = array();
				}
				array_push($idMap[$record['species_id']], $record['id']);
			}
		}
		$result->close();
		
		//link trees nodes
		foreach($parents as $childId => $parentId) {
			$nodes[$childId]->parent = $nodes[$parentId];
			array_push($nodes[$parentId]->childs, $nodes[$childId]);
		}
		
		//replace ids with objects in result map
		foreach($idMap as $speciesId => $leavesIds) {
			foreach ($leavesIds as $nodeId) {
				$source = $nodes[$nodeId];
				while(isset($source->parent)) {
					$source = $source->parent;
				}
				$speciesleaves[$speciesId][$source->name] = $nodes[$nodeId];
			}
		}
		
		return $speciesleaves;
	}
}
?>